/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-20 11:15:46
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-20 11:21:20
 * @FilePath: \gogamewebserver\goGameWebServer\internal\platform\platformOppo.go
 * @Description: 文件功能描述
 */
package platform

import (
	"encoding/json"
	"fmt"
	"goGameWebServer/internal/common/config"
	"goGameWebServer/internal/common/utils"
	"io"
	"net/http"
)

// 微信登录返回的会话信息
type OppoSession struct {
	Code  int          `json:"errCode"`
	Msg   string       `json:"errMsg"`
	Datat OppoUserData `json:"userInfo"`
}

type OppoUserData struct {
	OpenId        string `json:"userId"`
	UserName      string `json:"userName"`
	Avatar        string `json:"avatar"`
	Location      string `json:"location"`
	Constellation string `json:"constellation"`
	Age           string `json:"age"`
	Sex           string `json:"sex"`
}

type PlatformOppo struct {
	PlatformBase
}

func (p *PlatformOppo) Login(code string, option *config.PlatformOption) (output map[string]interface{}, err error) {
	// 1. 通过code获取微信会话信息
	session, err := p.GetSession(option.AppPrivateKey, option.AppSecret, option.AppPackageName, code)
	if err != nil {
		return output, err
	}
	output = make(map[string]interface{})
	output["open_id"] = session.Datat.OpenId
	return output, nil
}

// 通过code获取微信会话信息
func (p *PlatformOppo) GetSession(privateKey string, appSecret string, packageName string, code string) (*OppoSession, error) {
	nowTime := utils.GetNowTimestampNanoSecond()
	signStr := fmt.Sprintf("`appKey=%s&appSecret=%s&pkgName=%s&timeStamp=%d&token=%s`",
		privateKey, appSecret, packageName, nowTime, code)
	signature := utils.MD5Hex(signStr)
	url := fmt.Sprintf("https://play.open.oppomobile.com/instant-game-open/userInfo?pkgName=%s&token=%s&timeStamp=%d&sign=%s&version=1.0.0",
		packageName, code, nowTime, signature)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var session OppoSession
	if err := json.Unmarshal(body, &session); err != nil {
		return nil, err
	}

	if session.Code != 0 {
		return nil, fmt.Errorf("OppoAPI错误: %d %s", session.Code, session.Msg)
	}

	return &session, nil
}

func NewPlatformOppo() *PlatformOppo {
	return &PlatformOppo{
		PlatformBase: PlatformBase{},
	}
}
